package code;

import code.TreeNode;

import java.util.Arrays;

public class IsAVL_day16 {


    public static void main(String[] args) {
        Integer[] nums = new Integer[]{1, 2, 2, 3, null, null, 3, 4, null, null, 4};
        TreeNode root = new TreeNode();
        root = root.createTree(nums);
        boolean res = isAVL(root);
        System.out.println(res);
    }

    public static boolean isAVL(TreeNode root) {
        if (root == null) {return true;}
        int leftHeight;
        if (root.left == null) {
            leftHeight = 0;
        } else {
            leftHeight = treeHeight(root.left);
        }
        int rightHeight;
        if (root.right == null) {
            rightHeight = 0;
        } else {
            rightHeight = treeHeight(root.right);
        }
        if (Math.abs(leftHeight - rightHeight) > 1) {
            return false;

        } else {

            if( !isAVL(root.left) ){return false;}
            return isAVL(root.right);

        }
    }

    public static int treeHeight(TreeNode root) {
        if (root == null) return 0;
        return 1 + Math.max(treeHeight(root.left), treeHeight(root.right));
    }
}
